<?php

class ArticleController extends Controller
{
    public $tag = '';
    public $tagjsfile = '';
	public function actionIndex()
	{
		$criteria = new CDbCriteria();
		$criteria->order = 'createtime desc';
                $tag=$_GET['tagname'];
                if($tag !=''){
                    $criteria->condition='tag=:tag';
                    $criteria->params=array(':tag'=>$tag);
                }

		$count = Article::model()->count($criteria);
		
		$pager = new CPagination($count);
		$pager->pageSize = 40;
		$pager->applyLimit($criteria);

		$artList = Article::model()->findAll($criteria);
		$this->render('index',array('pages'=>$pager,'list'=>$artList));
	}
	/**
     * view article .
     *
     * @param   int    $id
     * @return  void
     */
	public function actionView(){
                $this->layout = '//layouts/artileleft';
		if(!isset($_GET['id']) || !(int)$_GET['id'])
			$this->redirect(array('article/index'));
                $id = (int)$_GET['id'];
		$article = Article::model()->find('id=:id',array(':id'=>$id));
		if(!$article) $this->redirect(array('article/index'));
               
                Article::model()->updateCounters(array('click'=>1),"id=$id");
                if($article->tag !=''){
                    $this->tag = $article->tag;
                }elseif($article->category->name != ''){
                    $this->tag = $article->category->name;
                }else{
                    $this->tag = Yii::app()->params['defaultkw'];
                }
                $py = new Pinyin();
				$filename = $py->str2py($this->tag);
				if(!$filename){
					$filename = date('Ymd',time());
				}
                $this->tagjsfile = $filename.'.js';
		$this->render('view',array('article'=>$article));
	}
      /**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Article('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Article']))
			$model->attributes=$_GET['Article'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	public function actionCategory(){
		if(!isset($_GET['id']) || !(int)$_GET['id'])
			$this->redirect(array('article/index'));
		$cate = Category::model()->find('id=:id',array(':id'=>(int)$_GET['id']));
		if(!$cate) $this->redirect(array('article/index'));

		$criteria = new CDbCriteria();
		$criteria->order = 'createtime desc';
		$criteria->condition = 'cateid=:id';
		$criteria->params = array(':id'=>$cate->id);
		$count = Article::model()->count($criteria);

		$pager = new CPagination($count);
		$pager->pageSize = 40;
		$pager->applyLimit($criteria);

		$artList = Article::model()->findAll($criteria);
		$this->render('category',array('cate'=>$cate,'pages'=>$pager,'artList'=>$artList));
	}
 /**
  * 添加文章.
  * @param   array    $data
  * @return  void
  */
	public function actionAdd(){
		$form = new Article();

		if(isset($_POST['Article']))
		{
			$data = $_POST['Article'];
			$type = Category::model()->find('id=:id',array(':id'=>(int)$data['cateid']));
			foreach(Yii::app()->params[$type->keyfile] as $key){
				$data['text'] = preg_replace('/(.*[^(<a.*>)])('.$key[0].')(.*[^<\/a>])/','${1}<a target="_blank" href="'.$key[1].'">${2}</a>${3}',$data['text']);
			}
			$form->attributes=$data;
			// validate user input and redirect to the previous page if valid
			if($form->validate()){
				$form->save();
				$this->redirect(array('article/index'));
			}else{
				var_dump($form->getErrors());
			}
				
		}
		$this->render('add',array('formModel'=>$form));
	}

       /**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
//                $form = new Article();
		$form=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Article']))
		{
			$data = $_POST['Article'];
			$type = Category::model()->find('id=:id',array(':id'=>(int)$data['cateid']));
			foreach(Yii::app()->params[$type->keyfile] as $key){
				$data['text'] = preg_replace('/(.*[^(<a.*>)])('.$key[0].')(.*[^<\/a>])/','${1}<a target="_blank" href="'.$key[1].'">${2}</a>${3}',$data['text']);
			}
			$form->attributes=$data;
			// validate user input and redirect to the previous page if valid
			if($form->validate()){
				$form->save();
				$this->redirect(array('article/index'));
			}else{
				echo "<pre>";
				print_r($form->getErrors());
				echo "</pre>";
				Yii::app()->end();
			}
		}

		$this->render('update',array(
			'formModel'=>$form,
		));
	}
	public function actionGetdata(){
		print_r($_POST);
	}

	public function accessRules(){
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','category'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('add','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','add','update'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	
	}

	public function filters()
	{
		return array(
			'accessControl',
		);
	}
        /**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Article::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
        /**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='articleform')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

}